<template>
  <div class="p-6">
    <a-card>
      <!-- 搜索和操作栏 -->
      <div class="mb-4 flex justify-between">
        <a-space>
          <a-input-search
            v-model:value="searchText"
            placeholder="搜索渠道名称/ID"
            style="width: 200px"
            @search="handleSearch"
          />
          <a-select
            v-model:value="channelType"
            style="width: 120px"
            placeholder="渠道类型"
            @change="handleSearch"
          >
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="alipay">支付宝</a-select-option>
            <a-select-option value="wechat">微信支付</a-select-option>
          </a-select>
        </a-space>
        <a-button type="primary" @click="handleAdd">
          <template #icon><plus-outlined /></template>
          新建渠道
        </a-button>
      </div>

      <!-- 渠道列表 -->
      <a-table
        :columns="columns"
        :data-source="channelList"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <!-- 渠道名称 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'name'">
            <div class="flex items-center">
              <img :src="record.icon" class="w-8 h-8 mr-2 rounded" />
              <div>
                <div class="font-medium">{{ record.name }}</div>
                <div class="text-gray-500 text-sm">ID: {{ record.channelId }}</div>
              </div>
            </div>
          </template>

          <!-- 渠道类型 -->
          <template v-if="column.key === 'type'">
            <a-tag :color="record.type === 'alipay' ? 'blue' : 'green'">
              {{ record.type === 'alipay' ? '支付宝' : '微信支付' }}
            </a-tag>
          </template>

          <!-- 费率 -->
          <template v-if="column.key === 'rate'">
            {{ record.rate }}%
          </template>

          <!-- 状态 -->
          <template v-if="column.key === 'status'">
            <a-badge
              :status="record.status === 'active' ? 'success' : 'error'"
              :text="record.status === 'active' ? '已启用' : '已禁用'"
            />
          </template>

          <!-- 操作 -->
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a @click="handleConfig(record)">配置</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定要删除这个渠道吗？"
                @confirm="handleDelete(record)"
              >
                <a class="text-red-500">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新建/编辑渠道弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalType === 'add' ? '新建渠道' : '编辑渠道'"
      @ok="handleModalOk"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="渠道名称" name="name">
          <a-input v-model:value="formData.name" placeholder="请输入渠道名称" />
        </a-form-item>
        <a-form-item label="渠道类型" name="type">
          <a-select v-model:value="formData.type" placeholder="请选择渠道类型">
            <a-select-option value="alipay">支付宝</a-select-option>
            <a-select-option value="wechat">微信支付</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="渠道图标" name="icon">
          <a-upload
            v-model:file-list="fileList"
            :before-upload="beforeUpload"
            :max-count="1"
          >
            <a-button>
              <upload-outlined /> 上传图标
            </a-button>
          </a-upload>
        </a-form-item>
        <a-form-item label="费率(%)" name="rate">
          <a-input-number
            v-model:value="formData.rate"
            :min="0"
            :max="100"
            :precision="2"
            :step="0.1"
          />
        </a-form-item>
        <a-form-item label="渠道描述" name="description">
          <a-textarea
            v-model:value="formData.description"
            placeholder="请输入渠道描述"
            :rows="4"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 渠道配置弹窗 -->
    <a-modal
      v-model:open="configModalVisible"
      title="渠道配置"
      width="800px"
      @ok="handleConfigOk"
    >
      <a-form
        ref="configFormRef"
        :model="configFormData"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="AppID" name="appId">
          <a-input v-model:value="configFormData.appId" placeholder="请输入AppID" />
        </a-form-item>
        <a-form-item label="AppSecret" name="appSecret">
          <a-input-password
            v-model:value="configFormData.appSecret"
            placeholder="请输入AppSecret"
          />
        </a-form-item>
        <a-form-item label="商户号" name="merchantId">
          <a-input v-model:value="configFormData.merchantId" placeholder="请输入商户号" />
        </a-form-item>
        <a-form-item label="API密钥" name="apiKey">
          <a-input-password
            v-model:value="configFormData.apiKey"
            placeholder="请输入API密钥"
          />
        </a-form-item>
        <a-form-item label="回调地址" name="notifyUrl">
          <a-input v-model:value="configFormData.notifyUrl" placeholder="请输入回调地址" />
        </a-form-item>
        <a-form-item label="证书文件" name="certFile">
          <a-upload
            v-model:file-list="certFileList"
            :before-upload="beforeCertUpload"
            :max-count="1"
          >
            <a-button>
              <upload-outlined /> 上传证书
            </a-button>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, UploadOutlined } from '@ant-design/icons-vue'
import type { TablePaginationConfig } from 'ant-design-vue'

// 表格列定义
const columns = [
  {
    title: '渠道名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '渠道类型',
    dataIndex: 'type',
    key: 'type',
  },
  {
    title: '费率',
    dataIndex: 'rate',
    key: 'rate',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
  },
]

// 测试数据
const channelList = ref([
  {
    id: 1,
    name: '支付宝服务商',
    channelId: 'ALIPAY_ISV_001',
    type: 'alipay',
    icon: 'https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg',
    rate: 0.6,
    status: 'active',
    createTime: '2024-01-01 12:00:00',
    description: '支付宝服务商渠道',
  },
  {
    id: 2,
    name: '微信支付服务商',
    channelId: 'WECHAT_ISV_001',
    type: 'wechat',
    icon: 'https://res.wx.qq.com/a/wx_fed/assets/res/OTE0YTAw.png',
    rate: 0.6,
    status: 'active',
    createTime: '2024-01-02 12:00:00',
    description: '微信支付服务商渠道',
  },
  {
    id: 3,
    name: '支付宝直连',
    channelId: 'ALIPAY_DIRECT_001',
    type: 'alipay',
    icon: 'https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg',
    rate: 0.38,
    status: 'inactive',
    createTime: '2024-01-03 12:00:00',
    description: '支付宝直连渠道',
  },
])

// 搜索和筛选
const searchText = ref('')
const channelType = ref('')
const loading = ref(false)

// 分页
const pagination = ref<TablePaginationConfig>({
  total: 3,
  current: 1,
  pageSize: 10,
})

// 弹窗相关
const modalVisible = ref(false)
const modalType = ref<'add' | 'edit'>('add')
const formRef = ref()
const formData = ref({
  name: '',
  type: undefined,
  icon: '',
  rate: 0,
  description: '',
})
const fileList = ref([])

// 配置弹窗相关
const configModalVisible = ref(false)
const configFormRef = ref()
const configFormData = ref({
  appId: '',
  appSecret: '',
  merchantId: '',
  apiKey: '',
  notifyUrl: '',
})
const certFileList = ref([])

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入渠道名称' }],
  type: [{ required: true, message: '请选择渠道类型' }],
  rate: [{ required: true, message: '请输入费率' }],
}

// 搜索
const handleSearch = () => {
  // TODO: 实现搜索逻辑
  console.log('搜索:', searchText.value, channelType.value)
}

// 表格变化
const handleTableChange = (pag: TablePaginationConfig) => {
  pagination.value = pag
  // TODO: 实现分页逻辑
}

// 新建渠道
const handleAdd = () => {
  modalType.value = 'add'
  formData.value = {
    name: '',
    type: undefined,
    icon: '',
    rate: 0,
    description: '',
  }
  modalVisible.value = true
}

// 编辑渠道
const handleEdit = (record: any) => {
  modalType.value = 'edit'
  formData.value = { ...record }
  modalVisible.value = true
}

// 配置渠道
const handleConfig = (record: any) => {
  configFormData.value = {
    appId: 'test_app_id',
    appSecret: 'test_app_secret',
    merchantId: 'test_merchant_id',
    apiKey: 'test_api_key',
    notifyUrl: 'https://example.com/notify',
  }
  configModalVisible.value = true
}

// 删除渠道
const handleDelete = (record: any) => {
  // TODO: 实现删除逻辑
  message.success('删除成功')
}

// 上传前检查
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('只能上传图片文件！')
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB！')
  }
  return isImage && isLt2M
}

// 证书上传前检查
const beforeCertUpload = (file: File) => {
  const isCert = file.name.endsWith('.pem') || file.name.endsWith('.p12')
  if (!isCert) {
    message.error('只能上传证书文件！')
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('证书大小不能超过 2MB！')
  }
  return isCert && isLt2M
}

// 弹窗确认
const handleModalOk = () => {
  formRef.value?.validate().then(() => {
    // TODO: 实现保存逻辑
    message.success(modalType.value === 'add' ? '创建成功' : '更新成功')
    modalVisible.value = false
  })
}

// 配置弹窗确认
const handleConfigOk = () => {
  configFormRef.value?.validate().then(() => {
    // TODO: 实现保存逻辑
    message.success('配置保存成功')
    configModalVisible.value = false
  })
}

onMounted(() => {
  // TODO: 加载数据
})
</script>

<style scoped>
.ant-upload-list-picture-card .ant-upload-list-item {
  padding: 8px;
  border: 1px solid #d9d9d9;
  border-radius: 2px;
}
</style>